package com.jzo2o.foundations.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.dto.response.ServeCategoryResDTO;
import com.jzo2o.foundations.model.dto.response.ServeSimpleResDTO;
import com.jzo2o.foundations.service.IHomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class HomeServiceImpl implements IHomeService {

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private ServeMapper serveMapper;

    /**
     * 首页区域服务列表查询
     * @param regionId
     * @return
     */
    @Caching(
            cacheable = {
                    //返回数据为空，则缓存空值30分钟，这样可以避免缓存穿透
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON,key ="#regionId" ,
                            unless ="#result.size()>0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),

                    //返回值不为空，则永久缓存数据
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON,key ="#regionId" ,
                            unless ="#result.size()==0",cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
    @Override
    public List<ServeCategoryResDTO> queryServeIconCategoryByRegionIdCache(Long regionId) {
        //1、检查当前区域是否启用
        Region region = regionMapper.selectById(regionId);
        if(ObjectUtil.isEmpty(region) || ObjectUtil.notEqual(region.getActiveStatus(), FoundationStatusEnum.ENABLE.getStatus())){
            return Collections.emptyList();
        }
    
        //2、首页服务列表查询,调用Dao执行查询
        List<ServeCategoryResDTO> list = serveMapper.findServeIconCategoryByRegionId(regionId);
        if(CollUtil.isEmpty(list)){
            return Collections.emptyList();
        }
    
        //3、提取前2个服务类型和前4个服务列表
        list=CollUtil.sub(list,0,(Math.min(list.size(), 2)));
        list.forEach(v->{
            List<ServeSimpleResDTO> serveList = v.getServeResDTOList();
            serveList=CollUtil.sub(serveList,0, Math.min(serveList.size(), 4));
            v.setServeResDTOList(serveList);
        });
        return list;
    }
}